import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:meco/common/index.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:meco/common/data/repositories/user_repository.dart';
import 'package:meco/common/data/services/user_service.dart';

class LoginController extends GetxController {
  LoginController();

  // 存储库
  final UserRepository _userRepository = UserRepository();

  // 用户服务
  final UserService _userService = Get.find<UserService>();

  // 表单控制器
  final TextEditingController emailController = TextEditingController();
  final TextEditingController passwordController = TextEditingController();

  // 焦点控制器
  final FocusNode emailFocusNode = FocusNode();
  final FocusNode passwordFocusNode = FocusNode();

  // 表单状态
  final RxBool obscurePassword = true.obs;

  // 表单全局key
  final formKey = GlobalKey<FormState>();

  // 切换密码显示
  void togglePasswordVisibility() {
    obscurePassword.value = !obscurePassword.value;
  }

  // 执行登录
  void login() async {
    // 检查输入是否完整
    if (emailController.text.isEmpty) {
      EasyLoading.showError('Username is required');
      return;
    }
    if (passwordController.text.isEmpty) {
      EasyLoading.showError('Password is required');
      return;
    }

    EasyLoading.show(status: 'Logging in...');

    try {
      // 调用存储库登录方法
      final user = await _userRepository.login(
        username: emailController.text.trim(),
        password: passwordController.text,
      );

      if (user == null) {
        EasyLoading.dismiss();
        EasyLoading.showError('Invalid username or password');
        return;
      }

      // 保存用户登录状态
      await _userService.saveLoginState(user);

      EasyLoading.showSuccess('Login successful');
      EasyLoading.dismiss();

      Get.back();

      // _userService.navigateBackAfterLogin();
    } catch (e) {
      EasyLoading.dismiss();
      EasyLoading.showError('Login failed: ${e.toString()}');
    }
  }

  // 跳转到注册页面
  void goToRegister() {
    Get.toNamed(Routes.register);
  }

  @override
  void onInit() {
    super.onInit();
    emailController.text = 'jack';
    passwordController.text = '123456';
  }

  @override
  void onClose() {
    emailController.dispose();
    passwordController.dispose();
    emailFocusNode.dispose();
    passwordFocusNode.dispose();
    super.onClose();
  }
}
